import { i18n } from 'boot/i18n'
import { getMenuValue } from 'pages/Menu/field-convert'
import { defineStore } from 'pinia'
import { Notify, uid } from 'quasar'
import { ajaxData } from 'src/api'
import { clearDictAndRemoteData } from 'src/enum/ajaxRemoteData.js'
import { clearStore, getStore, setStore } from 'src/utils/storage'
import { arrayToMap, isInIframe, mapToArray } from 'src/utils/utils.js'
import { tagsStores } from 'stores/tags-stores'
import { dynamicRouter } from 'src/router/dynamicRouter'

const prefixList = ['/authMenu', '/authRole', '/cfgDict', '/memberOrg', '/memberPost', '/memberUser', '/operLog']
const FormatMenus = (menus = [], LMenus = [], TMenus = [], parentId = '') => {
  for (const menu of menus) {
    const menuId = getMenuValue(menu, 'menuId') || uid(), path = getMenuValue(menu, 'path')
    const tempMenu = {
      meta: {
        menuId, remark: getMenuValue(menu, 'remark'), menuIcon: getMenuValue(menu, 'menuIcon'),
        menuZhCn: getMenuValue(menu, 'menuZhCn'), menuEnUs: getMenuValue(menu, 'menuEnUs'),
        menuCode: getMenuValue(menu, 'menuCode'), menuType: getMenuValue(menu, 'menuType'),
        serviceId: getMenuValue(menu, 'serviceId'), parentIds: getMenuValue(menu, 'parentIds') || parentId
      },
      children: void 0, component: void 0, name: `menu_${menuId}`,
      path: (path.startsWith('/') ? path : `/${path}`).replace(/\/\//g, '/')
    }
    // 调整系统管理菜单路径
    if (prefixList.includes(tempMenu.path)) tempMenu.path = `/SystemCtrl${tempMenu.path}`
    // 获得 list 子菜单 以作路由注册
    const list = getMenuValue(menu, 'children') || []
    if (list && list.length) {
      tempMenu.children = []
      TMenus.push(tempMenu)
      FormatMenus(list, LMenus, tempMenu.children, tempMenu.meta.menuId)
    } else {
      LMenus.push(tempMenu)
      TMenus.push(tempMenu)
    }
  }
  return { LMenus, TMenus }
}

export const userStores = defineStore('userStores', {
  state: () => ({
    breadcrumbs: getStore('breadcrumbs') || {},
    btns: arrayToMap(getStore('btns'), 'permission_'),
    listMenus: getStore('listMenus') || [],
    OSSPath: getStore('OSSPath') || '',
    serviceList: getStore('serviceList') || [],
    serviceMenu: {}, refreshMenus: true,
    token: getStore('Token', 'L') || '',
    treeMenus: getStore('treeMenus') || [],
    userInfo: getStore('userInfo') || {}
  }),
  getters: {},
  actions: {
    SET_USERINFO (userInfo) {
      this.userInfo = userInfo
      setStore('userInfo', userInfo)
    },

    SET_SERVICELIST (serviceList) {
      this.serviceList = serviceList
      setStore('serviceList', serviceList)
    },

    SET_BREADCRUMBS (breadcrumbs) {
      this.breadcrumbs = breadcrumbs
      setStore('breadcrumbs', breadcrumbs)
    },

    SET_TOKEN (token) {
      this.token = token
      setStore('Token', token, 'L')
    },

    SET_OSSPATH (OSSPath) {
      this.OSSPath = OSSPath
      setStore('OSSPath', OSSPath)
    },

    SET_BTNS (btns = []) {
      if (btns instanceof Map) {
        this.btns = btns
        return setStore('btns', mapToArray(btns, 'keys'))
      }
      if (btns instanceof Array) {
        this.btns = arrayToMap(btns, 'permission_')
        setStore('btns', btns)
      }
    },

    async LoginByName (loginForm = {}) { // 根据用户名登录
      return new Promise((resolve, reject) => {
        loginForm.containServiceList = true
        const { getOSS, ...params } = loginForm
        const url = loginForm.url ? loginForm.url : '/auth/api/login'
        ajaxData('post', url, params).then(res => {
          setStore('userName', res.userVO.loginName)
          this.SET_TOKEN(res.authToken)
          this.SET_USERINFO(res.userVO)
          this.SET_SERVICELIST(res.serviceList)
          if (getOSS) this.GetOSSPath()
          res.userVO.done = () => {
            !isInIframe() && Notify.create({
              position: 'top-right', icon: 'insert_emoticon',
              message: `Hi，${res.userVO.nickName} ${i18n.t('WelcomeBack')}`, type: 'positive'
            })
          }
          resolve(res.userVO)
        }).catch(error => reject(error))
      })
    },

    async GetOSSPath () {
      return new Promise((resolve, reject) => {
        ajaxData('get', '/oss/api/ossUploadRecord/serverHost', {}).then(res => {
          this.SET_OSSPATH(res)
          resolve(res)
        }).catch(error => reject(error))
      })
    },

    async GetBtns (serviceId = '') {
      return new Promise((resolve, reject) => {
        const { id } = this.breadcrumbs || {}
        serviceId = serviceId || id
        const SM = this.serviceMenu[serviceId]
        if (!this.refreshMenus && SM && SM.btns) return resolve(SM.btns)
        ajaxData('get', '/auth/api/currentUserPermissions', { serviceId }).then(res => {
          this.SET_BTNS(res)
          if (SM) SM.btns = res
          else this.serviceMenu[serviceId] = { btns: res }
          resolve(res)
        }).catch(error => reject(error))
      })
    },

    async GetMenus (serviceId = '', router) {
      const { id } = this.breadcrumbs || {}
      serviceId = serviceId || id
      await this.GetBtns(serviceId).then()
      return new Promise((resolve, reject) => {
        const SM = this.serviceMenu[serviceId]
        if (!this.refreshMenus && SM && SM.menu) {
          this.treeMenus = SM.menu.TMenus
          setStore('treeMenus', this.treeMenus)
          resolve(SM.menu)
          return
        }
        this.refreshMenus = false
        ajaxData('get', '/auth/api/currentUserTreeMenus', { serviceId }).then(res => {
          const menu = FormatMenus(res)
          if (!menu.TMenus.length || !menu.LMenus.length) return resolve(menu)
          dynamicRouter(menu.LMenus, router)
          const tempListMenus = this.listMenus.filter(el => el.meta?.serviceId !== serviceId)
          tempListMenus.push(...menu.LMenus)
          this.listMenus = tempListMenus
          setStore('listMenus', this.listMenus)
          this.treeMenus = menu.TMenus
          setStore('treeMenus', this.treeMenus)
          if (SM) SM.menu = menu
          else this.serviceMenu[serviceId] = { menu }
          resolve(menu)
        }).catch(error => reject(error))
      })
    },

    async LOGOUT (callback = void 0) { // 退出登录
      return new Promise(resolve => {
        this.SET_TOKEN('')
        this.SET_USERINFO({})
        callback && callback()
        tagsStores().SET_TAGS()
        this.listMenus = []
        this.treeMenus = []
        this.SET_SERVICELIST([])
        this.SET_BREADCRUMBS(void 0)
        clearDictAndRemoteData()
        clearStore()
        resolve(true)
      })
    }
  }
})